<template>
  <div class="chat-assistant">
    <!-- 右下角聊天按钮 -->
    <div class="chat-logo-container" @click="toggleChat">
      <img
        src="/mars-frontend/images/fire.JPG"
        alt="AI助手"
        title="点击打开AI助手"
        class="chat-logo"
      >
      <span v-if="hasNewMessage" class="chat-notification-badge">!</span>
    </div>

    <!-- 聊天容器 -->
    <div v-if="isChatVisible" class="chat-container-bottom show">
      <div class="chat-header">
        <h4>AI助手 - {{ currentModelName }}</h4>
        <button type="button" @click="closeChat" class="chat-close-btn">×</button>
      </div>

      <div class="chat-messages" ref="chatMessages">
        <div
          v-for="message in messages"
          :key="message.id"
          :class="['chat-message', message.type + '-message']"
        >
          <div class="message-content" v-html="message.content"></div>
          <div v-if="message.questions && message.questions.length > 0" class="suggested-questions">
            <div class="questions-title">相关问题：</div>
            <div class="question-buttons">
              <button
                v-for="(question, index) in message.questions"
                :key="index"
                @click="handleQuestionClick(question)"
                class="question-btn"
              >
                {{ question }}
              </button>
            </div>
          </div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>

      <div class="chat-input-area">
        <div class="chat-controls">
          <label class="chat-context-switch">
            <input
              type="checkbox"
              v-model="includeContext"
              @change="onContextChange"
            >
            包含地图上下文
          </label>
          <button
            type="button"
            @click="clearMessages"
            class="btn btn-sm btn-default"
          >
            清空对话
          </button>
        </div>

        <div class="chat-input-group">
          <input
            type="text"
          
            v-model="inputMessage"
            @keypress.enter="sendMessage"
            placeholder="输入你的问题..."
            maxlength="500"
            class="form-control"
            ref="chatInput"
          >
          <button
            type="button"
            @click="sendMessage"
            class="btn btn-primary"
            :disabled="isLoading"
          >
            {{ isLoading ? '发送中...' : '发送' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue'
import api from '../api/index.js'

// 为组件添加name，以便keep-alive可以正确缓存
defineOptions({
  name: 'ChatAssistant'
})

// 类型定义
interface ChatAction {
  type: 'recenter' | 'toggle_layer' | 'change_projection' | 'zoom_to' | 'change_body'
  lon?: number
  lat?: number
  layerId?: string
  enabled?: boolean
  projection?: string
  level?: number
  body?: string
}

interface MapContext {
  currentBody: string
  projection: string
  centerLon: number
  centerLat: number
  zoomLevel: number
  resolution: number
  mousePosition: { lon: number, lat: number }
  visibleLayers: Array<{ id: string, name: string }>
}

// 响应式数据
const isChatVisible = ref(false)
const hasNewMessage = ref(false)
const inputMessage = ref('')
const isLoading = ref(false)
const includeContext = ref(true)
const chatMessages = ref<HTMLElement>()
const chatInput = ref<HTMLInputElement>()

// 从配置文件获取API URL
const apiUrl = ref('') // 将在组件挂载时从配置文件加载

// 消息列表
const messages = ref<Array<{
  id: string
  type: 'user' | 'assistant' | 'system'
  content: string
  time: string
  questions?: string[]
}>>([
  {
    id: '1',
    type: 'system',
    content: '你好！我是"小火"，可以帮你解答关于火星相关的问题。你可以问我关于当前地图、图层、地名等任何问题。',
    time: new Date().toLocaleTimeString()
  }
])

// 计算属性
const currentModelName = computed(() => {
  return '小火数字助手'
})

// 方法
const toggleChat = () => {
  isChatVisible.value = !isChatVisible.value
  if (isChatVisible.value) {
    hasNewMessage.value = false
    nextTick(() => {
      scrollToBottom()
      chatInput.value?.focus()
    })
  }
}

const closeChat = () => {
  isChatVisible.value = false
}

const scrollToBottom = () => {
  if (chatMessages.value) {
    chatMessages.value.scrollTop = chatMessages.value.scrollHeight
  }
}

// 解析链接格式，将 \url{https://xxx} 转换为文献引用格式
const parseLinks = (text: string): { content: string, references: string[] } => {
  const references: string[] = []
  let referenceIndex = 1

  // 匹配 \url{https://xxx} 格式
  const urlRegex = /\\url\{([^}]+)\}/g
  const content = text.replace(urlRegex, (match, url) => {
    references.push(url)
    const index = referenceIndex++
    return `<sup><a href="${url}" target="_blank" rel="noopener noreferrer" style="color: #007bff; text-decoration: none;">[${index}]</a></sup>`
  })

  return { content, references }
}

const addMessage = (type: 'user' | 'assistant' | 'system', content: string, questions?: string[]) => {
  const { content: parsedContent, references } = parseLinks(content)

  // 如果有参考文献，添加到内容末尾
  let finalContent = parsedContent
  if (references.length > 0) {
    finalContent += '<div class="references" style="margin-top: 10px; padding-top: 10px; border-top: 1px solid #e0e0e0; font-size: 0.9em; color: #666;">'
    finalContent += '<strong>参考文献：</strong><br>'
    references.forEach((url, index) => {
      finalContent += `[${index + 1}] <a href="${url}" target="_blank" rel="noopener noreferrer" style="color: #007bff; text-decoration: underline;">${url}</a><br>`
    })
    finalContent += '</div>'
  }

  const message = {
    id: Date.now().toString(),
    type,
    content: finalContent,
    time: new Date().toLocaleTimeString(),
    questions: questions || []
  }
  messages.value.push(message)
  nextTick(() => {
    scrollToBottom()
  })
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  // 检查 API URL 是否已加载，如果没有则尝试从 window 获取
  if (!apiUrl.value) {
    if (window.chatAssistant_URL) {
      apiUrl.value = window.chatAssistant_URL
      console.log('从 window.chatAssistant_URL 重新加载 API URL:', apiUrl.value)
    } else {
      addMessage('system', '错误：API URL 未配置，请检查配置文件或刷新页面重试。')
      console.error('API URL 未加载，请检查配置文件和网络连接')
      console.error('window.chatAssistant_URL:', window.chatAssistant_URL)
      return
    }
  }

  const userMessage = inputMessage.value.trim()
  inputMessage.value = ''

  // 添加用户消息
  addMessage('user', userMessage)

  // 显示加载状态
  isLoading.value = true
  const thinkingId = Date.now().toString()
  addMessage('system', '正在思考...')

  try {
    // 构建请求数据
    const requestData = {
      message: userMessage,
      context: includeContext.value ? getMapContext() : null,
      history: messages.value.slice(-10).map(msg => ({
        type: msg.type,
        content: msg.content,
        timestamp: msg.time
      }))
    }

    // 发送请求
    console.log('Sending request to:', apiUrl.value)
    const response = await fetch(apiUrl.value, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData)
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()

    // 移除"正在思考"消息
    messages.value = messages.value.filter(msg => msg.id !== thinkingId)

    // 添加AI回复，包含questions
    addMessage('assistant', result.message || result.reply || '抱歉，我无法理解你的问题。', result.questions)

    // 如果有图片，显示图片
    if (result.image_url) {
      addMessage('assistant', `<img src="${result.image_url}" alt="AI生成的图片" class="chat-image" @click="showImageModal">`)
    }

    // 如果有建议的操作，执行它们
    if (result.actions) {
      executeChatActions(result.actions)
    }

  } catch (error) {
    console.error('Chat error:', error)
    // 移除"正在思考"消息
    messages.value = messages.value.filter(msg => msg.id !== thinkingId)
    addMessage('system', '抱歉，AI助手暂时无法使用，请稍后再试。')
  } finally {
    isLoading.value = false
  }
}

const clearMessages = () => {
  messages.value = [{
    id: '1',
    type: 'system',
    content: '你好！我是"小火"，可以帮你解答关于火星相关的问题。你可以问我关于当前地图、图层、地名等任何问题。',
    time: new Date().toLocaleTimeString()
  }]
}

const onContextChange = () => {
  console.log('Context enabled:', includeContext.value)
}

// 处理问题点击
const handleQuestionClick = (question: string) => {
  inputMessage.value = question
  sendMessage()
}

// 执行聊天建议的操作
const executeChatActions = (actions: ChatAction[]) => {
  if (!actions || !Array.isArray(actions)) {
    return
  }

  console.log('执行聊天建议操作:', actions)

  actions.forEach((action) => {
    try {
      switch (action.type) {
        case 'recenter':
          if (action.lon !== undefined && action.lat !== undefined) {
            console.log('执行重定位操作:', action.lon, action.lat)
            // 通过iframe访问lunaserv.js中的recenter函数
            const iframe = document.querySelector('iframe[src*="mars-frontend"]') as HTMLIFrameElement
            if (iframe && iframe.contentWindow) {
              const iframeWindow = iframe.contentWindow as any
              if (iframeWindow.recenter) {
                iframeWindow.recenter(action.lon, action.lat, true, true)
                console.log('重定位操作已执行')
              } else {
                console.warn('iframe中未找到recenter函数')
              }
            } else {
              console.warn('未找到mars-frontend iframe')
            }
          }
          break
        case 'toggle_layer':
          if (action.layerId) {
            console.log('执行图层切换操作:', action.layerId, action.enabled)
            const iframe = document.querySelector('iframe[src*="mars-frontend"]') as HTMLIFrameElement
            if (iframe && iframe.contentWindow) {
              const iframeWindow = iframe.contentWindow as any
              const layerSwitch = iframeWindow.document.getElementById('lunaserv_switch_' + action.layerId)
              if (layerSwitch) {
                layerSwitch.checked = action.enabled !== false
                if (iframeWindow.refresh_layer_visibilities) {
                  iframeWindow.refresh_layer_visibilities()
                }
                console.log('图层切换操作已执行')
              } else {
                console.warn('未找到图层开关:', action.layerId)
              }
            }
          }
          break
        case 'change_projection':
          if (action.projection) {
            console.log('执行投影切换操作:', action.projection)
            const iframe = document.querySelector('iframe[src*="mars-frontend"]') as HTMLIFrameElement
            if (iframe && iframe.contentWindow) {
              const iframeWindow = iframe.contentWindow as any
              const projectionMenu = iframeWindow.document.getElementById('lunaserv_projection_switch_menu')
              if (projectionMenu) {
                projectionMenu.value = action.projection
                if (iframeWindow.recenter) {
                  const centerLon = iframeWindow.center_longitude || 0
                  const centerLat = iframeWindow.center_latitude || 0
                  const currentBody = iframeWindow.current_body || 'MOON'
                  iframeWindow.recenter(centerLon, centerLat, true, true, currentBody, action.projection)
                }
                console.log('投影切换操作已执行')
              } else {
                console.warn('未找到投影菜单')
              }
            }
          }
          break
        case 'zoom_to':
          if (action.level !== undefined) {
            console.log('执行缩放操作:', action.level)
            const iframe = document.querySelector('iframe[src*="mars-frontend"]') as HTMLIFrameElement
            if (iframe && iframe.contentWindow) {
              const iframeWindow = iframe.contentWindow as any
              if (iframeWindow.map) {
                iframeWindow.map.zoomTo(action.level)
                console.log('缩放操作已执行')
              } else {
                console.warn('iframe中未找到map对象')
              }
            }
          }
          break
        case 'change_body':
          if (action.body) {
            console.log('执行天体切换操作:', action.body)
            const iframe = document.querySelector('iframe[src*="mars-frontend"]') as HTMLIFrameElement
            if (iframe && iframe.contentWindow) {
              const iframeWindow = iframe.contentWindow as any
              const bodyMenu = iframeWindow.document.getElementById('lunaserv_body_switch_menu')
              if (bodyMenu) {
                bodyMenu.value = action.body
                if (iframeWindow.recenter) {
                  iframeWindow.recenter(0, 0, true, true, action.body)
                }
                console.log('天体切换操作已执行')
              } else {
                console.warn('未找到天体菜单')
              }
            }
          }
          break
        default:
          console.warn('未知的操作类型:', action.type)
      }
    } catch (error) {
      console.error('执行操作时出错:', error)
    }
  })
}

// 获取地图上下文
const getMapContext = (): MapContext => {
  try {
    // 尝试从iframe获取真实的地图上下文
    const iframe = document.querySelector('iframe[src*="mars-frontend"]') as HTMLIFrameElement
    if (iframe && iframe.contentWindow) {
      const iframeWindow = iframe.contentWindow as any

      if (iframeWindow.map) {
        const visibleLayers = []

        // 获取可见图层
        if (iframeWindow.map.layers) {
          for (let i = 0; i < iframeWindow.map.layers.length; i++) {
            const layer = iframeWindow.map.layers[i]
            if (layer.getVisibility && layer.getVisibility() && layer.unique_id) {
              visibleLayers.push({
                id: layer.unique_id,
                name: layer.name
              })
            }
          }
        }

        // 获取鼠标位置
        let mousePos = { lon: 0, lat: 0 }
        if (iframeWindow.map.getCenter) {
          const center = iframeWindow.map.getCenter()
          if (center && iframeWindow.unproject) {
            const geoLocation = iframeWindow.unproject(center)
            mousePos = { lon: geoLocation.lon, lat: geoLocation.lat }
          }
        }

        return {
          currentBody: iframeWindow.current_body || 'MOON',
          projection: iframeWindow.current_projection || 'ORTHO',
          centerLon: iframeWindow.center_longitude || 0,
          centerLat: iframeWindow.center_latitude || 0,
          zoomLevel: iframeWindow.map.getZoom ? iframeWindow.map.getZoom() : 0,
          resolution: iframeWindow.resolution_meters_per_pixel || 0,
          mousePosition: mousePos,
          visibleLayers: visibleLayers
        }
      }
    }
  } catch (error) {
    console.warn('无法获取地图上下文:', error)
  }

  // 如果无法获取真实上下文，返回默认值
  return {
    currentBody: 'MOON',
    projection: 'ORTHO',
    centerLon: 0,
    centerLat: 0,
    zoomLevel: 0,
    resolution: 0,
    mousePosition: { lon: 0, lat: 0 },
    visibleLayers: []
  }
}

// 监听新消息
watch(() => messages.value.length, (newLength, oldLength) => {
  if (newLength > oldLength && !isChatVisible.value) {
    hasNewMessage.value = true
  }
})

onMounted(async () => {
  console.log('Chat assistant mounted')
  console.log('检查 window.chatAssistant_URL:', window.chatAssistant_URL)
  
  // 等待一小段时间，确保 ipURLConfig.js 已加载
  await new Promise(resolve => setTimeout(resolve, 100))
  
  await api.loadApiConfig()

  console.log('Loading API config from:', window.config_URL)
  
  // 从配置文件加载API URL
  if (window.chatAssistant_URL) {
    apiUrl.value = window.chatAssistant_URL
    console.log('✓ Chat assistant API URL loaded from config:', window.chatAssistant_URL)
  } else {
    console.warn('✗ 未找到 chatAssistant_URL 配置')
    console.warn('  请检查 ipURLConfig.js 文件是否已正确加载')
    console.warn('  当前 window.chatAssistant_URL:', window.chatAssistant_URL)
    // 如果配置加载失败，使用默认值
    apiUrl.value = 'http://127.0.0.1:3001/api/chat'
    console.warn('  使用默认 API URL:', apiUrl.value)
  }
  
  // 最终确认 apiUrl 已设置
  if (!apiUrl.value) {
    console.error('❌ API URL 仍然未设置，使用强制默认值')
    apiUrl.value = window.chatAssistant_URL || 'http://127.0.0.1:3001/api/chat'
  }
  console.log('最终 API URL:', apiUrl.value)
})
</script>

<style scoped>
/* 聊天助手样式 */

.chat-assistant {
  position: relative;
}

/* 覆盖一些样式以适配Vue组件 */
.chat-logo-container {
  position: fixed;
  bottom: 20px;
  right: 70px;
  z-index: 1000;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.chat-logo-container:hover {
  transform: scale(1.1);
}

.chat-logo {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  transition: box-shadow 0.3s ease;
}

.chat-logo:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
}

.chat-notification-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #d9534f;
  color: white;
  font-size: 12px;
  font-weight: bold;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 18px;
  text-align: center;
  animation: pulse 2s infinite;
}

.chat-container-bottom {
  position: fixed;
  bottom: 90px;
  right: 70px;
  width: 350px;
  height: 500px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  z-index: 999;
  display: none;
  flex-direction: column;
  overflow: hidden;
}

.chat-container-bottom.show {
  display: flex;
  animation: slideInUp 0.3s ease-out;
}

@keyframes slideInUp {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.chat-header {
  flex-shrink: 0;
  background-color: #007bff;
  color: white;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 12px 12px 0 0;
}

.chat-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.chat-close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  font-weight: bold;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s ease;
}

.chat-close-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #ffffff;
  min-height: 0;
}

.chat-message {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
}

.chat-message .message-content {
  padding: 8px 12px;
  border-radius: 12px;
  max-width: 80%;
  word-wrap: break-word;
  line-height: 1.4;
  font-size: 14px;
}

.chat-message .message-time {
  font-size: 11px;
  color: #6c757d;
  margin-top: 2px;
  padding: 0 4px;
}

.user-message {
  align-items: flex-end;
}

.user-message .message-content {
  background-color: #007bff;
  color: white;
  border-bottom-right-radius: 4px;
}

.user-message .message-time {
  text-align: right;
}

.assistant-message {
  align-items: flex-start;
}

.assistant-message .message-content {
  background-color: #e9ecef;
  color: #212529;
  border-bottom-left-radius: 4px;
}

.assistant-message .message-time {
  text-align: left;
}

.system-message {
  align-items: center;
}

.system-message .message-content {
  background-color: #fff3cd;
  color: #856404;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  text-align: center;
  max-width: 90%;
  font-style: italic;
}

.system-message .message-time {
  text-align: center;
}

.chat-input-area {
  flex-shrink: 0;
  padding: 16px;
  background-color: #f8f9fa;
  border-top: 1px solid #dee2e6;
  border-radius: 0 0 12px 12px;
}

.chat-controls {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 12px;
}


.chat-context-switch {
  margin: 0;
  font-weight: normal;
  color: #6c757d;
  display: flex;
  align-items: center;
  gap: 4px;
}

.chat-controls > button {
  align-self: flex-end;
  margin-top: 4px;
}

.chat-input-group {
  display: flex;
  gap: 8px;
}

.chat-input-group .form-control {
  flex: 1;
  border-radius: 20px;
  border: 1px solid #ced4da;
  padding: 8px 16px;
  font-size: 14px;
}

.chat-input-group .btn {
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 14px;
  white-space: nowrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container-bottom {
    width: calc(100vw - 40px);
    height: calc(100vh - 120px);
    bottom: 80px;
    right: 20px;
    left: 20px;
  }

  .chat-logo-container {
    bottom: 15px;
    right: 15px;
  }

  .chat-logo {
    width: 50px;
    height: 50px;
  }
}

/* 建议问题样式 */
.suggested-questions {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #e0e0e0;
}

.questions-title {
  font-size: 0.8em;
  color: #666;
  margin-bottom: 8px;
  font-weight: 600;
}

.question-buttons {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.question-btn {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #dee2e6;
  border-radius: 6px;
  padding: 8px 12px;
  font-size: 0.8em;
  color: #495057;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: left;
  line-height: 1.3;
  word-wrap: break-word;
}

.question-btn:hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
  border-color: #adb5bd;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.question-btn:active {
  transform: translateY(0);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 移动端问题按钮样式 */
@media (max-width: 768px) {
  .question-btn {
    font-size: 0.75em;
    padding: 6px 10px;
  }
}
</style>
